package com.zzxx.wechat.common.handle;


import com.zzxx.wechat.exception.BusinessException;
import com.zzxx.wechat.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;




@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public R<Void> error(BusinessException e) {
        return R.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {

        BindingResult bindingResult = exception.getBindingResult();

        FieldError fieldError = bindingResult.getFieldErrors().get(0);

        return R.error(fieldError.getDefaultMessage());
    }


    //1 处理所有的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R<Void> error(Exception e) {
        log.error("全局异常处理Exception:", e);
        return R.error();
    }


}
